# -*- coding: utf-8 -*-
# @author okumura@laurus.co.jp

from gaeo.controller import BaseController
from libs.laurus.action import before_action
from google.appengine.ext.webapp.util import login_required
from model.pigeon import Pigeon
from libs.django.core.paginator import QuerySetPaginator, InvalidPage, EmptyPage

class SentController(BaseController):
    def before_action(self):
        before_action(self)

    @login_required
    def index(self):
        query = Pigeon.all()
        query.filter('from_user =', self.user)
        query.filter('status =', 'Sent')
        query.order('-post_at')
        paginator = QuerySetPaginator(query, 20)

        if self.params.get('page'):
            page = int(self.params.get('page'))
        else:
            page = 1

        try:
            self.pigeons = paginator.page(page)
        except (EmptyPage, InvalidPage):
            self.pigeons = paginator.page(paginator.num_pages)

    @login_required
    def detail(self):
        #IDが指定されていなければリダイレクト
        if not self.params.get('id'):
            self.redirect('/')
            return
        #伝書鳩が取得できなければリダイレクト
        pigeon = Pigeon.get_by_id(int(self.params.get('id')))
        if not pigeon:
            self.redirect('/')
            return
        #送信元がcurrent_userでなければリダイレクト
        if pigeon.from_user != self.user:
            selr.redirect('/inbox')
            return
        #テンプレートに登録
        self.pigeon = pigeon

